<!-- 维修执行页面 -->
<template>
  <div class="pending-repair">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :search.sync="search"
        :data="data"
        :page.sync="page"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        :permission="permissionList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
        :row-style="tableRowClassName"
      >
        <template slot="menuLeft">
          <div class="repair-data">
            <div class="wait-repair">
              待维修 <span>{{ statisticsObj.waitRepairQuantity }} </span>
            </div>
            <div class="have-repair">
              当日已维修 <span>{{ statisticsObj.haveRepairQuantity }} </span>
            </div>
          </div>
        </template>
        <template slot="menuRight">
          <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出 </el-button>
        </template>
        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" size="small" @click="handleWaitRepair(row)">维修执行</el-button>
        </template>
      </avue-crud>
    </basic-container>
    <!--    <el-card class="box-card">-->
    <!--      <div class="card-list">-->
    <!--        <li style="margin-bottom: 10px">-->
    <!--          待维修：<span style="font-size: inherit; background: #ffff00">{{ statisticsObj.repairCount }}</span>-->
    <!--        </li>-->
    <!--        <li>-->
    <!--          已维修：<span style="font-size: inherit; background: #caf982">{{ statisticsObj.repairedCount }}</span>-->
    <!--        </li>-->
    <!--      </div>-->
    <!--    </el-card>-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <export-comp ref="exportComp" page-api-url="mes-product/mro-repair-confirm/page" :option="option" :page="page" :query="exportParams" file-name="待维修列表"></export-comp>
    <!--    <el-dialog title="可视化配置" :visible.sync="dialogVisible" width="50%" :before-close="handleClose" append-to-body="true" top="3vh">-->
    <!--      &lt;!&ndash; 这里放置弹窗内容 &ndash;&gt;-->
    <!--      <div class="sail-header-dialog-content">-->
    <!--        <div class="titleLeft">-->
    <!--          <i class="el-icon-vertical-bar avue-group__icon"></i>-->
    <!--          <h4>停留时间</h4>-->
    <!--        </div>-->
    <!--        <div class="form-content" v-for="(item, index) in formData" :key="item.timer">-->
    <!--          <avue-form ref="warehousePropertiesForm" v-model="formData[index]" :option="formOption" class="rules-form">-->
    <!--            <template slot="sortLabel">-->
    <!--              <strong>排序{{ index + 1 }}</strong>-->
    <!--            </template>-->
    <!--            <template slot="sort">-->
    <!--              <span class="color-start">*</span>-->
    <!--              <el-input style="width: 100px" v-model="formData[index].rangeStart" controls-position="right" @change="(val) => handleInputChange(val, index, 'rangeStart')" />-->
    <!--              到-->
    <!--              <el-input style="width: 100px" v-model="formData[index].rangeEnd" controls-position="right" @change="(val) => handleInputChange(val, index, 'rangeEnd')" />-->
    <!--              小时-->
    <!--            </template>-->

    <!--            <template slot="color">-->
    <!--              <avue-input-color placeholder="请选择颜色标识" v-model="formData[index].color" @change="(val) => handleSetColor(val, index)"></avue-input-color>-->
    <!--            </template>-->
    <!--            <template slot="btn">-->
    <!--              <el-button v-if="index === formData.length - 1" type="text" size="small" icon="el-icon-circle-plus" @click="handleAdd()" class="btn-add"></el-button>-->
    <!--              <el-button v-else type="text" size="small" icon="el-icon-remove" class="btn-add" @click="handleDelete(index)"></el-button>-->
    <!--            </template>-->
    <!--          </avue-form>-->
    <!--        </div>-->
    <!--      </div>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="dialogVisible = false" size="small">取消</el-button>-->
    <!--        <el-button type="primary" @click="saveConfig" size="small">保存</el-button>-->
    <!--      </span>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import { getPageList, getDetail, getRepairStatistics, setColor, getColor } from '@/api/repair/pendingRepair';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import exportComp from '@/components/export-comp';
import { filterEmptyValues } from '@/util/util';
import { getParamDetail } from '@/api/system/param';
export default {
  name: 'pendingRepair',
  components: {
    CommonModalTemplate,
    exportComp
  },
  data() {
    return {
      paramValue: false,
      dialogVisible: false,
      pageCode: 'pendingRepair',
      colorInfo: {},
      formData: [
        {
          timer: new Date().getTime(),
          rangeStart: '',
          rangeEnd: '',
          color: ''
        }
      ],
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '80',
        column: [
          {
            label: '排序1',
            prop: 'sort',
            span: 12
          },
          {
            label: '颜色标识',
            prop: 'color',
            type: 'color',
            span: 8,
            labelWidth: 100,
            rules: [
              {
                required: true,
                message: '请选择颜色标识',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '',
            prop: 'btn',
            labelWidth: 0,
            span: 4
          }
        ]
      },
      isAuto: false,
      activeName: 'first',
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      viewDialog: false,
      query: {},
      search: {},
      statisticsObj: {},
      loading: false,
      selectionList: [],
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      exportParams: {},
      option: {
        header: true,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        // searchMenuSpan: 12,
        searchMenuPosition: 'right',
        border: true,
        index: true,
        indexLabel: '序号',
        selection: false,
        dialogClickModal: false,
        searchLabelWidth: 120,
        labelWidth: 120,
        searchSpan: 6,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        searchBtn: true,
        emptyBtn: true,
        viewBtn: false,
        menuWidth: 100,
        columnBtn: false,
        // refreshBtn: false,
        column: [
          {
            label: '工单号',
            prop: 'workOrderNo',
            search: true,
            searchOrder: 2
          },
          {
            label: '序列号',
            prop: 'productSn',
            search: true,
            searchSpan: 6,
            searchOrder: 2,
            minWidth: 100
          },
          {
            label: '产品编码',
            prop: 'productPartNo',
            search: true
          },
          {
            label: '产品名称',
            prop: 'productPartName'
          },
          {
            label: '产品型号',
            search: true,
            prop: 'productPartModel'
          },
          {
            label: '登记产线',
            prop: 'lineName',
            search: true
          },
          {
            label: '登记工序',
            prop: 'routeName',
            // type: 'search',
            search: true
            // searchOrder: 4
            // appendClick: () => {
            //   this.openRouteModel();
            // },
            // change: ({ value }) => {
            //   if (!value) {
            //     this.search.fromRouteCode = '';
            //     this.search.fromRouteName = '';
            //   }
            // }
          },
          {
            label: '登记工位',
            prop: 'stationName',
            search: true
          },
          // {
          //   label: '不良现象',
          //   prop: 'failureName',
          //   searchOrder: 5,
          //   search: true
          // },
          {
            label: '不良现象',
            prop: 'badPhenomenonName'
          },
          {
            label: '登记说明',
            prop: 'registerDescription'
          },
          {
            label: '登记人员',
            prop: 'registerUserName'
          },
          {
            label: '登记时间',
            prop: 'registerTime',
            searchType: 'datetimerange',
            search: true,
            searchSpan: 8,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '判定说明',
            prop: 'confirmDescription'
          },
          {
            label: '判定人员',
            prop: 'confirmUserName'
          },
          {
            label: '判定时间',
            prop: 'confirmTime',
            searchType: 'datetimerange',
            search: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            searchSpan: 8,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '停留时长(h)',
            prop: 'stayDuration'
          },
          {
            label: '已维修次数',
            prop: 'repairTimes'
          },
          {
            label: '停留时长(h)开始',
            prop: 'stayStartDuration',
            search: true,
            searchType: 'number',
            precision: 2,
            searchSpan: 4,
            min: 0,
            hide: true
          },
          {
            label: '停留时长(h)结束',
            prop: 'stayEndDuration',
            search: true,
            hide: true,
            searchType: 'number',
            precision: 2,
            searchSpan: 4,
            min: 0
          }

          // {
          //   label: '进维修时间',
          //   minWidth: 120,
          //   prop: 'judgeTime',
          //   type: 'datetime',
          //   search: true,
          //   searchSpan: 8,
          //   searchOrder: 18,
          //   searchType: 'datetimerange',
          //   format: 'yyyy-MM-dd HH:mm:ss',
          //   valueFormat: 'yyyy-MM-dd HH:mm:ss',
          //   startPlaceholder: '开始日期',
          //   endPlaceholder: '结束日期'
          // }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.repairExec_view, false)
      };
    },
    ids() {}
  },
  async mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    // await this.getConfigInfo();
    // await this.onLoad(this.page);
    getRepairStatistics().then((res) => {
      let data = res.data.data;
      this.statisticsObj = data;
    });
    this.paramConfig();
  },
  methods: {
    paramConfig() {
      getParamDetail({
        paramKey: 'product.isJumpRepairConfirmation'
      }).then((res) => {
        let data = res.data.data;
        if (this._get(data, 'paramValue') === 'false') {
          this.paramValue = false;
        } else {
          this.paramValue = true;
        }
      });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.registerTime) {
        params.registerStartTime = params.registerTime[0];
        params.registerEndTime = params.registerTime[1];
        delete params.registerTime;
      }
      if (params.confirmTime) {
        params.judgeStartTime = params.confirmTime[0];
        params.judgeEndTime = params.confirmTime[1];
        delete params.confirmTime;
      }

      if ((params.stayEndDuration && !params.stayStartDuration) || (params.stayStartDuration && !params.stayEndDuration)) {
        this.$message.warning('请输入停留时长');
        done();
        return;
      }
      if (params.stayEndDuration < 0 || params.stayStartDuration < 0) {
        this.$message.warning('停留时长(h)开始或者停留时长(h)结束不能小于0');
        done();
        return;
      }
      this.query = params;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      // params.statusStr = '6';
      // params.queryType = 'WAITING_REPAIR';
      this.loading = true;
      getPageList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
        this.loading = false;
        this.selectionClear();
      });
    },
    tableRowClassName({ row, column, rowIndex }) {
      const res = this.hoursDifference(row.judgeTime);
      const color = this.getValueLessThanNumber(res);
      return {
        backgroundColor: color || ''
      };
    },
    getValueLessThanNumber(hour) {
      if (this.colorInfo.key && this.colorInfo.key.length) {
        // 找到第一个小于给定数字的键
        const smallerKey = this.colorInfo.key.find((key) => hour < key);
        // 返回对应键的值
        return smallerKey ? this.colorInfo.map[smallerKey] : null;
      } else {
        return null;
      }
    },
    hoursDifference(targetDateTime) {
      // 将目标日期时间和当前日期时间转换为 Moment 对象
      const targetMoment = this.$moment(targetDateTime, 'YYYY-MM-DD HH:mm:ss');
      const currentMoment = this.$moment(new Date(), 'YYYY-MM-DD HH:mm:ss');

      // 计算两个日期时间之间的毫秒数差异
      const diffMilliseconds = currentMoment.diff(targetMoment);

      // 将毫秒数差异转换为小时数
      const diffHours = this.$moment.duration(diffMilliseconds).asHours();

      // 向下取整，得到整数小时数
      const roundedDiffHours = Math.floor(diffHours);
      return roundedDiffHours;
    },
    convertFormDataToText() {
      // 创建一个空对象，用于存储转换后的数据
      const result = {};
      const keyArr = [];
      // 遍历 formData 数组
      for (let i = 0; i < this.formData.length; i++) {
        const item = this.formData[i];
        // 计算 rangeEnd - rangeStart，并获取颜色值
        const diff = Number(item.rangeEnd);
        const color = item.color;
        // 将结果添加到对象中
        keyArr.push(diff);
        result[diff] = color;
      }
      keyArr.sort((a, b) => a - b);
      // 返回转换后的对象
      return { map: result, key: keyArr };
    },
    handleWaitRepair(row) {
      this.$router.push({
        path: !this.paramValue ? `/repair/repairExecOperation` : '/repair/repairExecNoConfirm',
        query: {
          productSequenceNumber: encodeURI(row.productSn)
        }
      });
    },

    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'routeCode':
          this.search.fromRouteName = this._get(rowData, 'name', '');
          this.search.fromRouteCode = this._get(rowData, 'code', '');
          break;
        default:
          break;
      }
    },
    openRouteModel() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'routeCode';
      this.tableOption = {
        modalTitle: '选择工站信息（双击进行选择）',
        url: '/api/mes-product/apaas/workstation/page',
        isPage: false,
        index: false,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },

    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    async handleConfig() {
      await this.getConfigInfo();
      this.dialogVisible = true;
    },
    async getConfigInfo() {
      try {
        const res = await getColor(data);
        const data = res.data.data;
        this.formData = data.map((item) => {
          return {
            timer: item.id,
            rangeStart: item.rangeStart,
            rangeEnd: item.rangeEnd,
            color: item.color
          };
        });
        this.colorInfo = this.convertFormDataToText();
      } catch (e) {
        console.log(e);
      }
    },
    handleClose(done) {
      // 如果需要在关闭弹窗之前执行一些操作，可以在这里添加逻辑
      done(); // 关闭弹窗
    },
    handleAdd() {
      this.formData.push({
        timer: new Date().getTime(),
        rangeStart: 0,
        rangeEnd: 0,
        color: ''
      });
    },
    handleDelete(index) {
      // 删除指定索引的表单项
      this.formData.splice(index, 1);
    },
    handleInputChange(value, index, field) {
      try {
        const isValid = /^\d+$/.test(value);
        if (isValid) {
          // 如果输入值为正整数或0，更新数据
          this.formData[index][field] = parseInt(value, 10); // 转换为整数，确保类型正确
        } else {
          // 如果输入值不是正整数或0，提示用户
          this.$message.error('请输入一个正整数或0！');
          this.formData[index][field] = ''; // 可选：清除错误输入
        }

        // 获取当前表单项的起始时间和结束时间
        const rangeStart = this.formData[index].rangeStart;
        const rangeEnd = this.formData[index].rangeEnd;
        // copy 副本
        const formData = this._cloneDeep(this.formData[index]);
        // 如果结束时间小于或等于起始时间，则提示冲突信息，并将结束时间重置为0
        if (field === 'rangeEnd' && rangeEnd <= rangeStart) {
          this.$message.error(`排序${index + 1}时间有冲突，请重新编辑！`);
          formData.rangeEnd = null;
          this.$set(this.formData[index], 'rangeEnd', null);
        }
        // 如果是第一行，不需要继续验证
        if (index === 0) {
          return;
        }
        if (field === 'rangeStart') {
          // 获取上一行的起始时间
          const topEnd = this.formData[index - 1].rangeEnd;
          if (rangeStart <= topEnd) {
            this.$message.error(`排序${index + 1}和排序${index}时间有冲突，请重新编辑！`);
            this.$set(this.formData[index], 'rangeStart', null);
          }
        }
      } catch (e) {
        console.log(e);
      }
    },
    handleSetColor(val, index) {
      if (index === 0) {
        return;
      }
      const formData = this._cloneDeep(this.formData[index]);
      formData.splice(index, 1);
      const colorArr = formData.map((item) => item.color);
      if (val && colorArr.includes(val)) {
        this.$message.error('颜色标识重复，请重新选择不同的颜色');
        this.$set(this.formData[index], 'color', '');
      }
    },
    async saveConfig() {
      if (this.isFormDataPopulated()) {
        const data = this.formData.map((i) => {
          return { rangeStart: i.rangeStart, rangeEnd: i.rangeEnd, color: i.color };
        });
        try {
          const res = await setColor(data);
          this.$message.success('配置成功');
          await this.getConfigInfo();
          await this.onLoad(this.page);
          this.dialogVisible = false;
        } catch (e) {}
      }
    },

    isFormDataPopulated() {
      // 遍历 formData 数组
      return this.formData.some((item) => {
        // 检查每个对象的属性是否为空
        return item.rangeStart !== 0 || item.rangeEnd !== 0 || item.color !== '';
      });
    },
    handleExport() {
      const params = filterEmptyValues(this._cloneDeep(this.search));
      if (params.registerTime) {
        params.registerStartTime = params.registerTime[0];
        params.registerEndTime = params.registerTime[1];
        delete params.registerTime;
      }
      if (params.confirmTime) {
        params.judgeStartTime = params.confirmTime[0];
        params.judgeEndTime = params.confirmTime[1];
        delete params.confirmTime;
      }
      if ((params.stayEndDuration && !params.stayStartDuration) || (params.stayStartDuration && !params.stayEndDuration)) {
        this.$message.warning('请输入停留时长');
        done();
        return;
      }
      if (params.stayEndDuration < 0 || params.stayStartDuration < 0) {
        this.$message.warning('停留时长(h)开始或者停留时长(h)结束不能小于0');
        done();
        return;
      }
      this.exportParams = params;
      this.$refs.exportComp.visible = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.repair-data {
  width: 400px;
  height: 40px;
  font-size: 14px;
  display: flex;
  align-items: center;
  .wait-repair {
    width: 150px;
    height: 100%;
    color: rgba(0, 0, 0, 0.85);
    display: flex;
    align-items: center;
    span {
      color: #f59a23;
      margin-left: 12px;
    }
  }
  .have-repair {
    width: 250px;
    height: 100%;
    color: rgba(0, 0, 0, 0.85);
    display: flex;
    align-items: center;
    span {
      color: #70b603;
      margin-left: 12px;
    }
  }
}
</style>
